﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Logging;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SMARTHOTEL.Customers;
using SMARTHOTEL.Products;
using SMARTHOTEL.RoomMoneys;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace SMARTHOTEL.Cients
{
    /// <summary>
    /// 客户
    /// </summary>
    [ApiExplorerSettings(GroupName = "v2")]
    public class CientService : ApplicationService, ICientService
    {
        IRepository<Cient> repository;
        IRepository<Customer> repository1;
        IRepository<Membershipbenefits> repository2;
        IRepository<Membershipcard> repository3;

        public CientService(IRepository<Cient> repository, IRepository<Customer> repository1, IRepository<Membershipbenefits> repository2, IRepository<Membershipcard> repository3)
        {
            this.repository = repository;
            this.repository1 = repository1;
            this.repository2 = repository2;
            this.repository3 = repository3;
        }
        #region 客户列表
        /// <summary>
        /// 客户添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("InsertCient")]
        public async Task<ResultDto<bool>> InsertCient(InsertCientDto dto)
        {
            try
            {
                Cient cient = ObjectMapper.Map<InsertCientDto, Cient>(dto);
                await repository.InsertAsync(cient);
                return new ResultDto<bool> { Data = true, Code = StatusCode.Success, Msg = "添加成功" };
            }
            catch (Exception ex)
            {

                return new ResultDto<bool> { Data = false, Code = StatusCode.Faield, Msg = "添加失败" + ex.Message };
            }
        }
        /// <summary>
        /// 客户列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetCientList")]
        public async Task<ResultDto<ApiPage<CientDto>>> GetCientList(CientQuerycondition cient)
        {


            var list = from a in await repository.GetQueryableAsync()
                       join b in await repository1.GetQueryableAsync()
                       on a.CientId equals b.Id
                       select new CientDto
                       {
                           Id = a.Id,
                           CientId=a.CientId,
                           CustomerName=b.CustomerName,
                           NickCustomerName=b.NickCustomerName,
                           Statushierarchy =a.Statushierarchy,
                           Tags=a.Tags,
                           CardNumber=a.CardNumber,
                           CustomerPhone=b.CustomerPhone,
                           Availablebalance=a.Availablebalance,
                           Availablepoints=a.Availablepoints,
                           Totalspent=a.Totalspent,
                           Ordercount=a.Ordercount,
                           Refundamount=a.Refundamount,
                           Complaintcount=a.Complaintcount,
                           Status=a.Status,
                           CustomerSex=b.CustomerSex,
                           CustomerAge=b.CustomerAge,
                           CustomerIdCard=b.CustomerIdCard,

                       };

         
            ApiPage<CientDto> page = new ApiPage<CientDto>();
            page.TotalCount = list.Count();
            page.TotalPage=(int)Math.Ceiling(page.TotalCount*1.0/cient.Size);
            page.List = list.Skip(cient.Size * (cient.Index - 1)).Take(cient.Size).ToList() ;
            return new ResultDto<ApiPage<CientDto>>
            {
                Data =page,
                Code = StatusCode.Success,
                Msg = "查询成功"
            };
        }
        /// <summary>
        /// 更新客户状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
         [HttpPut("UpdateCientStatuesAsync")]
        public async Task<ResultDto<bool>> UpdateCientStatuesAsync(string id, int statues)
        {
            try
            {
                int i = 0;
                var ids = id.Split(',');
                foreach (var item in ids)
                {
                    var entity = await repository.GetAsync(x => x.Id == Guid.Parse(item));
                    if (entity == null)
                    {
                        continue;
                    }
                    else
                    {
                        entity.Status = Convert.ToBoolean(statues);
                        await repository.UpdateAsync(entity);
                    }
                    i++;
                }
                return new ResultDto<bool> { Data = true, Code = StatusCode.Success, Msg = "更新成功" };
            }
            catch (Exception ex)
            {
                return new ResultDto<bool> { Data = false, Code = StatusCode.Faield, Msg = "更新失败" };
            }
        }
        /// <summary>
        /// 导出客户信息
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> ExportExcel()
        {
            try
            {
                byte[] data = null;
                string contentType = new FileExtensionContentTypeProvider().Mappings[".xlsx"];
                string fileName = "客户信息列表.xlsx";

                // 新的Excel工作簿
                IWorkbook book = new XSSFWorkbook();
                // 创建一个sheet
                ISheet sheet = book.CreateSheet();
                // 创建第一行
                IRow row1 = sheet.CreateRow(0);

                // 给第一行的每一个单元格进行赋值
                row1.CreateCell(0).SetCellValue("客户姓名");
                row1.CreateCell(1).SetCellValue("昵称");
                row1.CreateCell(2).SetCellValue("手机");
                row1.CreateCell(3).SetCellValue("可用余额");
                row1.CreateCell(4).SetCellValue("可用积分");
                row1.CreateCell(5).SetCellValue("累计消费金额");
                row1.CreateCell(6).SetCellValue("累计消费次数");
                row1.CreateCell(7).SetCellValue("累计退款金额");
                row1.CreateCell(8).SetCellValue("累计维权次数");
                row1.CreateCell(9).SetCellValue("状态");

                // 获取数据
                var list = await repository.GetListAsync();
                var customerList = await repository1.GetListAsync();

                // 第二行
                int rowIndex = 1;

                foreach (var item in list)
                {
                    var customer = customerList.FirstOrDefault(c => c.Id == item.CientId);
                    if (customer != null)
                    {
                        IRow row = sheet.CreateRow(rowIndex);
                        row.CreateCell(0).SetCellValue(customer.CustomerName);
                        row.CreateCell(1).SetCellValue(customer.NickCustomerName);
                        row.CreateCell(2).SetCellValue(customer.CustomerPhone);
                        row.CreateCell(3).SetCellValue(item.Availablebalance.ToString());
                        row.CreateCell(4).SetCellValue(item.Availablepoints.ToString());
                        row.CreateCell(5).SetCellValue(item.Totalspent.ToString());
                        row.CreateCell(6).SetCellValue(item.Ordercount.ToString());
                        row.CreateCell(7).SetCellValue(item.Refundamount.ToString());
                        row.CreateCell(8).SetCellValue(item.Complaintcount.ToString());
                        row.CreateCell(9).SetCellValue(item.Status ? "有效" : "无效");

                        rowIndex++;
                    }
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    // 工作表写入内存流中
                    book.Write(ms);

                    // 内存流赋给数据字节数组中
                    data = ms.ToArray();
                }

                // 返回一个文件结果
                return new FileContentResult(data, contentType)
                {
                    FileDownloadName = fileName
                };
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion
        #region 会员权限
        /// <summary>
        /// 会员权益添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("InsertMembershipbenefits")]
        public async Task<ResultDto<bool>> InsertMembershipbenefits(InsertMembershipbenefitsDto dto)
        {
            try
            {
                Membershipbenefits cient = ObjectMapper.Map<InsertMembershipbenefitsDto, Membershipbenefits>(dto);
                await repository2.InsertAsync(cient);
                return new ResultDto<bool> { Data = true, Code = StatusCode.Success, Msg = "添加成功" };
            }
            catch (Exception ex)
            {

                return new ResultDto<bool> { Data = false, Code = StatusCode.Faield, Msg = "添加失败" + ex.Message };
            }
        }
        public async Task<ResultDto<List<GetMembershipbenefitsDto>>> GetMembershipbenefitsList()
        {
            var list= await repository2.GetListAsync();
           
            return new ResultDto<List<GetMembershipbenefitsDto>>
            {
                Data = ObjectMapper.Map<List<Membershipbenefits>, List<GetMembershipbenefitsDto>>(list),
                Code = StatusCode.Success,
                Msg = "添加成功"
            };
        }
        #endregion
        #region 会员卡管理
        /// <summary>
        /// 添加会员卡
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("InsertMembershipcard")]
        public async Task<ResultDto<bool>> InsertMembershipcard(InsertMembershipcardDto dto)
        {
            try
            {
                Membershipcard card = ObjectMapper.Map<InsertMembershipcardDto, Membershipcard>(dto);
                await repository3.InsertAsync(card);
                return new ResultDto<bool> { Data = true, Code = StatusCode.Success, Msg = "添加成功" };
            }
            catch (Exception ex)
            {

                return new ResultDto<bool> { Data = false, Code = StatusCode.Faield, Msg = "添加失败" + ex.Message };
            }
        }
        /// <summary>
        /// 查询会员卡号
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetMembershipcard")]
        public async Task<ResultDto<MembershipcardDto>> GetMembershipcard()
        {
            var card = await repository3.FirstOrDefaultAsync();
            return new ResultDto<MembershipcardDto>
            {
                Data = ObjectMapper.Map< Membershipcard, MembershipcardDto >(card),
                Code = StatusCode.Success,
                Msg="查询成功"
            };
            }


        #endregion
    }
}

